import Dialog from '../../miniprogram_npm/@vant/weapp/dialog/dialog';
import Toast from '../../miniprogram_npm/@vant/weapp/toast/toast';
import { clearAudioFn, formatFormList, setTabBarIndex } from '../../utils/hooks';
import * as Storage from '../../utils/storage';
import subPub from '../../utils/subPub';
import { debounce, getElement, initLocationPersmiss } from '../../utils/util';
const $api = require('../../request/api').API;
const app = getApp();
const innerAudioContext = wx.createInnerAudioContext();
// 获取去年今天的日期
const date = new Date();
const lastYear = new Date(date.getFullYear() - 1 + '-' + (date.getMonth() + 1) + '-' + date.getDate()).getTime();
Page({
  data: {
    fixedTopHeight: 100,
    userRole: 0,
    dataList: [],
    startPositionX: 0,
    startPositionY: 0,
    //分页相关
    pageNum: 1,
    pageSize: '',
    twoBeeperList: [{ id: -1, name: '周边服务' }], //两个呼叫器列表
    beeperList: [],
    beeperId: -1,
    businessList: [],
    businessId: '',
    mainFlag: 0,
    showFilter: false,
    showBeeperSearch: false,
    beeperKey: '',
    beeperScrollTop: 0, // 呼叫器搜索后需要置顶
    showDate: false,
    // 订单状态
    orderStatusList: [
      { text: '已接单待确认', value: 1 },
      { text: '商户已确认', value: 5 },
      { text: '服务员已确认', value: 10 },
      { text: '已出发', value: 11 },
      { text: '已到达', value: 12 },
      { text: '已回收', value: 13 },
      { text: '已取消', value: 15 },
      { text: '取消失败', value: 16 },
      { text: '已完成', value: 20 }
    ],

    //  下单时间
    orderDateList: [
      // { text: '下单时间', value: '' },
      { text: '今日', value: 1 },
      { text: '3天内', value: 3 },
      { text: '7天内', value: 7 },
      { text: '一个月内', value: 30 },
      { text: '两个月内', value: 60 },
      { text: '三个月内', value: 90 }
    ],
    orderScoreList: [
      { text: '五星评分', value: 5 },
      { text: '四星及以下', value: 4 }
    ],
    orderState: '',
    timeDate: '',
    totalScore: '',
    groupValue: '',
    beginDate: '',
    endDate: '',
    beginDateName: '',
    endDateName: '',
    maxDate: new Date().getTime(),
    minDate: lastYear,
    targetDate: '',
    type: 1, //表示是开始时间还是介绍时间
    // 格式化时间
    formatDate: function (type, value) {
      if (type === 'year') {
        return `${value}年`;
      }
      if (type === 'month') {
        return `${value}月`;
      }
      if (type === 'day') {
        return `${value}日`;
      }
      return value;
    },

    btnId: '',
    btnServerClassifyIds: '',
    queryType: '',
    // 选择支付弹框
    showPayDialog: false,
    // 支付方式
    payType: 1,
    // 选中的订单编号
    orderNo: '',
    // 加载
    loading: false,
    // 警报order ID
    alertOrderId: undefined
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: async function (options) {
    // 监听详情页面订单状态改变
    this.orderModifyStateId = subPub.on('orderModifyState', ({ orderId, orderState, payState, errorState }) => {
      const { dataList } = this.data;
      const index = dataList.findIndex(item => item.orderId == orderId);
      if (index == -1) return;
      const target = dataList[index];
      Object.assign(target, { orderState, payState, errorState });
      const prop = `dataList[${index}]`;
      this.setData({
        [prop]: target
      });
    });
  },
  onReady() {
    getElement('.top-sticky').then(res => {
      this.setData({
        fixedTopHeight: res[0].height
      });
    });
  },
  onShow: async function () {
    setTabBarIndex(2);
    !this.alreadyCome && (await this.getHJQList());
    const { beeperOrderId } = app.globalData;
    if (beeperOrderId) {
      // 如果存在beeperOrderId就选中那个呼叫器
      this.setData({
        loading: true,
        pageNum: 1,
        dataList: []
      });
      const { beeperList } = this.data;
      this.selectBeeper({ ...beeperList.find(item => item.id == beeperOrderId) });
      // 获取呼叫器信息
      delete app.globalData.beeperOrderId;
    } else if (!this.alreadyCome) {
      // 如果app.globalData.beeperOrderId不存在且是第一次进来
      this.selectBeeper({ ...this.data.beeperList[0] });
    }
    this.alreadyCome = true;
  },
  stopBubble() {},
  // 搜索
  searchOrder: debounce(function (e) {
    this.setData({
      groupValue: e.detail,
      pageNum: 1,
      showFilter: false
    });
    this.getData();
  }, 300),
  // 获取呼叫器列表数据
  async getHJQList() {
    let res = await $api.beeperList({ type: 2 });
    res = res.data.data || [];
    res = [{ id: -1, name: '周边服务' }, ...res];
    this.setData({
      beeperList: res
    });
  },
  // 获取呼叫器信息,并选中该呼叫器
  async getBeeperInfo(id) {
    let { twoBeeperList } = this.data;
    // twoBeeperList = [{id:-1,name:"周边服务"}]
    let mainFlag = 0;
    if (id !== -1) {
      let res = await $api.getBeeper({ id });
      res = res.data.data;
      mainFlag = res.mainFlag;
      const obj = { id, name: res.equipName, mainFlag };
      twoBeeperList.length > 1 ? (twoBeeperList[1] = obj) : twoBeeperList.push(obj);
    }
    this.setData({
      beeperId: id,
      mainFlag,
      twoBeeperList,
      pageNum: 1
    });
    this.getData();
  },
  // 搜索呼叫器
  handleSearchBeeper: debounce(async function (e) {
    const res = await $api.beeperList({ type: 2, value: e.detail });
    this.setData(
      {
        beeperList: res.data.data || []
      },
      () => {
        this.setData({
          beeperScrollTop: 0
        });
      }
    );
  }, 500),
  // 选中呼叫器
  selectBeeper(e) {
    let item = e.target ? e.target.dataset.item : e;
    let { twoBeeperList, beeperList } = this.data;
    if (!item) return;
    let { id, mainFlag } = item;
    if (twoBeeperList.length < 2) {
      if (id == -1) {
        beeperList.length && (twoBeeperList = [{ id: -1, name: '周边服务' }, { ...beeperList[1] }]);
      } else {
        twoBeeperList = [{ id: -1, name: '周边服务' }, { ...item }];
      }
    } else if (id != -1) {
      twoBeeperList = [{ id: -1, name: '周边服务' }, { ...item }];
    }
    // if(id==-1){
    //   if(twoBeeperList.length<2&&beeperList.length){
    //     twoBeeperList = [{ id: -1, name: "周边服务" }, { ...item }]
    //   }
    // }else{

    // }
    // const beeper = this.data.beeperList.find(item => item.id == detail.name)
    this.setData({
      beeperId: id,
      pageNum: 1,
      mainFlag: id == -1 ? 0 : mainFlag,
      showBeeperSearch: false,
      twoBeeperList
    });
    this.getData();
  },
  // 呼叫器弹框
  async showBeeperSearchPopup() {
    let { showBeeperSearch } = this.data;
    this.setData({
      showBeeperSearch: showBeeperSearch ? false : true,
      beeperKey: ''
    });
    this.getHJQList();
  },
  // 关闭呼叫器弹框
  closeBeeperSearchPopup() {
    this.setData({
      showBeeperSearch: false,
      beeperKey: ''
    });
  },
  // 去打印页面
  toPrint() {
    wx.navigateTo({
      url: '/subcontract/order/pages/print/index?beeperId=' + this.data.beeperId
    });
  },
  // 筛选
  showFilterPopup() {
    this.setData({
      showFilter: true
    });
  },
  closeFilterPopup() {
    this.setData({
      showFilter: false
    });
  },
  // 订单状态选择筛选
  statusChange(e) {
    let id = e.target.dataset.id;
    if (id) {
      this.setData({
        orderState: id,
        pageNum: 1
      });
    }
  },
  //  下单时间选择筛选
  dateChange(e) {
    let id = e.target.dataset.id;
    if (id) {
      this.setData({
        timeDate: id,
        pageNum: 1,
        endDate: '',
        beginDate: '',
        beginDateName: '',
        endDateName: ''
      });
    }
  },
  // 显示时间选择弹框
  showDatePopup(e) {
    let type = e.currentTarget.dataset.type;
    let targetDate = null;

    // 获取当前时间
    if (type == 1 && this.data.beginDate) {
      targetDate = this.data.beginDate;
    } else if (type == 2 && this.data.endDate) {
      targetDate = this.data.endDate;
    } else {
      targetDate = new Date().getTime();
    }

    // 确定可选时间范围
    if (type == 1 && this.data.endDate) {
      this.setData({
        maxDate: this.data.endDate,
        minDate: ''
      });
    } else if (type == 2 && this.data.beginDate) {
      this.setData({
        minDate: this.data.beginDate,
        maxDate: new Date().getTime()
      });
    } else {
      this.setData({
        minDate: lastYear,
        maxDate: new Date().getTime()
      });
    }

    this.setData({
      showDate: true,
      targetDate: targetDate,
      type: type
    });
  },
  closeDatePopup() {
    this.setData({
      showDate: false
    });
  },
  // 确认时间
  confirmDate(e) {
    if (this.data.type == 1) {
      this.setData({
        beginDate: e.detail,
        beginDateName: this.getDate(e.detail)
      });
    } else {
      this.setData({
        endDate: e.detail,
        endDateName: this.getDate(e.detail)
      });
    }

    this.setData({
      showDate: false,
      timeDate: ''
    });
  },
  getDate(date) {
    let time = new Date(date);
    let year = time.getFullYear();
    let month = time.getMonth() + 1;
    let day = time.getDate();
    return year + '-' + month + '-' + day;
  },
  // 评分等级
  scoreChange(e) {
    let id = e.target.dataset.id;
    if (id) {
      this.setData({
        totalScore: id,
        pageNum: 1
      });
    }
  },
  // 重置筛选
  resetFilter() {
    this.setData({
      timeDate: '',
      orderState: '',
      totalScore: '',
      endDate: '',
      beginDate: '',
      endDateName: '',
      beginDateName: ''
    });
  },
  // 确认过滤
  confirmFilter() {
    this.setData({
      pageNum: 1,
      showFilter: false
    });
    this.getData();
  },
  // 获取列表数据
  async getData() {
    let params = {
      pageNo: this.data.pageNum,
      pageSize: 10,
      orderState: this.data.orderState,
      date: this.data.timeDate,
      groupValue: this.data.groupValue,
      beginDate: this.data.timeDate ? '' : this.data.beginDateName,
      endDate: this.data.timeDate ? '' : this.data.endDateName,
      beeperId: this.data.beeperId
    };
    this.setData({
      loading: true
    });
    // 先停止播放声音
    this.stopAudio();
    try {
      let res = await $api.orderList(params);
      res = res.data.data;
      // 先判断有没有表单数据，且格式化一下
      res.list.forEach(item => {
        if (item.orderAttrs && item.orderAttrs.length) {
          item.orderAttrs = formatFormList(item.orderAttrs);
        }
      });
      this.setData({
        dataList: res.list,
        pageNum: res.pageNum,
        pageSize: res.pageSize,
        totalPage: res.totalPage
      });
      // 置顶
      wx.pageScrollTo({
        scrollTop: 0,
        duration: 0
      });
    } finally {
      this.setData({
        loading: false
      });
    }
  },
  // 拨打电话
  callPhone(e) {
    let phone = e.currentTarget.dataset.phone;
    wx.makePhoneCall({
      phoneNumber: phone, //仅为示例，并非真实的电话号码
      success: function () {
        console.log('拨打电话成功！');
      },
      fail: function () {
        console.log('拨打电话失败！');
      }
    });
  },
  // 去评价
  toEvaluate(e) {
    wx.navigateTo({
      url: '/subcontract/order/pages/evaluate/index?orderId=' + e.currentTarget.dataset.id
    });
  },
  // 结果查询
  async queryResult(e) {
    let res = await $api.listKlabReportUrl({ orderId: e.currentTarget.dataset.item.orderId });
    res = res.data.data || '';
    if (!res) {
      Toast.fail('暂未查询到结果');
      return;
    }
    wx.downloadFile({
      url: res,
      success: res2 => {
        wx.openDocument({
          filePath: res2.tempFilePath,
          fileType: 'pdf',
          showMenu: true
        });
      },
      fail(err) {
        console.log(err);
      }
    });
  },
  // 再来一单
  anotherOrder(e) {
    let item = e.currentTarget.dataset.item;
    let shopCartData = [];
    $api.againOrderInfo({ orderId: item.orderId }).then(res => {
      let data = res.data.data;
      data.goodsList.forEach(item2 => {
        shopCartData.push({
          ruleId: data.ruleId,
          businessId: data.businessId,
          businessName: data.businessName,
          id: item2.beeperBtnId,
          nums: item2.nums,
          salePrice: item2.salePrice,
          packageFee: item2.packageFee,
          mainImage: item2.images,
          fastFlag: item2.fastFlag,
          goodsId: item2.goodsId,
          serverId: item2.serverId,
          thirdClassifyId: item2.thirdClassifyId,
          variantId: item2.variantId,
          name: item2.name,
          goodsType: item2.goodsType,
          specVal: item2.strSpecVal,
          relationVariantId: item2.variantIds || [],
          relationNames:
            item2.oGRelations && item2.oGRelations.length ? item2.oGRelations.map(item => item.name).toString() : ''
        });
      });
      wx.setStorageSync('shopCartData', JSON.stringify(shopCartData));
      initLocationPersmiss().then(res => {
        app.globalData['btnList.beeperId'] = item.beeperId;
        app.globalData['btnList.latitude'] = res.location.lat;
        app.globalData['btnList.longitude'] = res.location.lng;
        app.globalData['btnList.btnId'] = data.btnId;
        app.globalData['btnList.btnServerClassifyIds'] = data.btnServerClassifyIds;
        app.globalData['btnList.queryType'] = data.queryType;
        wx.navigateTo({
          url: '/subcontract/home/pages/submitOrder/index?another=1'
        });
      });
    });
  },
  // 继续支付
  async continuePay(e) {
    let data = e.currentTarget.dataset.item;
    let mianFlag = this.data.mainFlag;
    if (data.beeperId) {
      let res = await this.getBeeperBalance(data.beeperId);
      if (
        mianFlag &&
        data.goodsType != 3 &&
        ((data.payState == 1 && data.realAmount < res) || (data.payState == 4 && data.lastAmount < res))
      ) {
        this.setData({
          showPayDialog: true,
          orderNo: data.orderNo,
          payType: 1
        });
      } else {
        this.setData({
          payType: 2,
          orderNo: data.orderNo
        });
        this.confrimPay();
      }
    } else {
      this.setData({
        payType: 2,
        orderNo: data.orderNo
      });
      this.confrimPay();
    }
  },
  // 支付方式
  payChange(val) {
    let type = val.currentTarget.dataset.type;
    this.setData({
      payType: type
    });
  },
  // 确认支付
  confrimPay() {
    let payType = this.data.payType;
    let params = {
      orderNos: this.data.orderNo,
      openId: wx.getStorageSync(Storage.USER_OPEN_ID),
      payType: payType
    };
    if (payType == 1) {
      Toast.loading({
        message: '支付中',
        forbidClick: true,
        mask: true
      });
    }
    $api.scanToPayWaitOrder(params).then(res => {
      let data = res.data.data;
      if (payType == 1) {
        Toast.success({
          message: '支付成功',
          forbidClick: true,
          mask: true
        });
        setTimeout(() => {
          this.getData();
        }, 1000);
      } else if (payType == 2) {
        let _this = this;
        wx.requestPayment({
          timeStamp: data.timeStamp,
          nonceStr: data.nonceStr,
          package: data.package,
          signType: data.signType,
          paySign: data.paySign,
          success: res => {
            Toast.success({
              message: '支付成功',
              forbidClick: true
            });
            setTimeout(() => {
              _this.getData();
            }, 1000);
          },
          fail: err => {
            Toast.fail({
              message: '支付失败',
              forbidClick: true
            });
          },
          complete: res => {}
        });
      }
    });
  },
  // 查询余额
  async getBeeperBalance(beeperId) {
    let params = {
      id: beeperId
    };
    let res = await $api.getBeeperBalance(params);
    return res.data.data;
  },
  toDetail(e) {
    let id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: '/subcontract/order/pages/details/index?orderId=' + id + '&mainFlag=' + this.data.mianFlag
    });
  },
  //刷新
  onRefresh() {
    //显示 loading 提示框。需主动调用 wx.hideLoading 才能关闭提示框
    wx.showLoading({
      title: '刷新中...'
    });
    this.setData({
      pageNum: 1
    });
    this.getData();

    setTimeout(() => {
      wx.showToast({
        title: '刷新成功'
      });
      wx.stopPullDownRefresh();
    }, 1000);
  },
  // 通过id获取索引
  getIndexById(arr, id) {
    let tempIndex = -1;
    arr.find((item, index) => {
      if (item.id == id) {
        tempIndex = index;
        return true;
      }
    });
    return tempIndex;
  },
  // 阻止图片滑动冒泡
  stopTouchendBubble() {},
  // 触屏开始滑动
  silderStart(e) {
    this.setData({
      startPositionX: e.changedTouches[0].clientX,
      startPositionY: e.changedTouches[0].clientY
    });
  },
  // 触屏结束滑动
  silderEnd(e) {
    let endPositionX = e.changedTouches[0].clientX;
    let endPositionY = e.changedTouches[0].clientY;
    let tempX = endPositionX - this.data.startPositionX;
    let tempY = Math.abs(endPositionY - this.data.startPositionY);
    let beeperList = this.data.beeperList;
    let index = this.getIndexById(beeperList, this.data.beeperId);
    let length = this.data.beeperList.length;
    if (tempX < -50 && index + 1 <= length - 1 && tempY < 30) {
      this.setData({
        pageNum: 1,
        beeperId: beeperList[index + 1].id
      });
      this.getData();
    }
    if (tempX > 50 && index - 1 >= 0 && tempY < 30) {
      this.setData({
        pageNum: 1,
        beeperId: beeperList[index - 1].id
      });
      this.getData();
    }
  },
  // 预览图片
  previewImg(e) {
    let val = e.currentTarget.dataset;
    wx.previewImage({
      current: val.url,
      urls: [...val.list]
    });
  },
  playAudio(e) {
    const { index2, index } = e.currentTarget.dataset;
    const { dataList } = this.data;
    const target = dataList[index].orderAttrs[index2];
    let isPlay = target.isPlay;
    this.stopAudio();
    if (isPlay) {
      target.isPlay = false;
      this.setData({
        dataList
      });
      return;
    } else {
      if (target.value) {
        innerAudioContext.src = target.value;
        innerAudioContext.play();
      }
      this.setData({
        dataList
      });
    }
    this.onPlay = () => {
      target.isPlay = true;
      this.setData({
        dataList
      });
    };
    this.onEnded = () => {
      target.isPlay = false;
      this.setData({
        dataList
      });
    };
    innerAudioContext.onPlay(this.onPlay);
    innerAudioContext.onEnded(this.onEnded);
  },
  stopAudio() {
    const { dataList } = this.data;
    let indexArr = [];
    dataList.find((item, index) => {
      return item.orderAttrs.find((item2, index2) => {
        if (item2.fieldType == 8 && item2.isPlay) {
          item2.isPlay = false;
          indexArr = [index, index2];
          return true;
        }
      });
    });
    clearAudioFn(innerAudioContext, { onPlay: this.onPlay, onEnded: this.onEnded });
    if (indexArr.length) {
      const prop = `dataList[${indexArr[0]}].orderAttrs[${indexArr[1]}].isPlay`;
      this.setData({
        [prop]: false
      });
    }
  },

  /**
   * 救援进度点击 前往救援详情界面
   * @param event
   */
  handleRescueProgressClick(event) {
    const { id } = event.currentTarget.dataset;
    wx.navigateTo({
      url: `/subcontract/order/pages/rescueProgress/index?orderId=${id}`
    });
  },

  /**
   * 解除警报
   */
  handleReleaseAlert(event) {
    const { id } = event.currentTarget.dataset;
    this.setData({
      alertOrderId: id
    });
    Dialog.confirm({
      title: '提示',
      showCancelButton: true,
      cancelButtonText: '误触发',
      confirmButtonText: '已处理',
      closeOnClickOverlay: true,
      message: '确定解除警报吗？'
    });
  },

  /**
   * 解除警报 - 已处理
   */
  handleAlarmLiftedProcess() {
    const { alertOrderId } = this.data;
    $api.orderCancelAlarm({ orderId: alertOrderId, cancelReason: 2 }).then(() => {
      wx.showToast({ title: '解除成功！' });
      this.setData({ alertOrderId: undefined });
    });
  },

  /**
   * 解除警报 - 误触
   */
  handleFalseAlarmRelease() {
    const { alertOrderId } = this.data;
    $api.orderCancelAlarm({ orderId: alertOrderId, cancelReason: 1 }).then(() => {
      wx.showToast({ title: '解除成功！' });
      this.setData({ alertOrderId: undefined });
    });
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {
    if (this.onPlay) {
      this.stopAudio();
      // clearAudioFn(innerAudioContext,{onPlay:this.onPlay,onEnded:this.onEnded})
    }
  },
  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    if (this.onPlay) {
      this.stopAudio();
      // clearAudioFn(innerAudioContext,{onPlay:this.onPlay,onEnded:this.onEnded})
    }
    subPub.off('orderModifyState', this.orderModifyStateId);
  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    //调用刷新时将执行的方法
    this.onRefresh();
  },
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    const { totalPage, pageNum } = this.data;
    if (totalPage <= pageNum) return;
    this.setData({
      pageNum: pageNum + 1
    });
    let params = {
      pageNo: this.data.pageNum,
      pageSize: 10,
      orderState: this.data.orderState,
      date: this.data.timeDate,
      groupValue: this.data.groupValue,
      beginDate: this.data.beginDateName,
      endDate: this.data.endDateName,
      beeperId: this.data.beeperId
    };
    let dataList = this.data.dataList;
    var dataConcat = [];
    $api
      .orderList(params)
      .then(res => {
        let list = res.data.data.list;
        if (list.length != 0) {
          dataConcat = dataList.concat(list);
          this.setData({
            dataList: dataConcat
          });
        } else {
          Toast('没有更多啦');
        }
      })
      .catch(err => {
        console.log('充值记录', err);
      });
  }
});
